package com.Iron.ProessorAop;

import com.Iron.Advice.EnhanceMethod;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class BeanPostProcessors implements BeanPostProcessor, ApplicationContextAware {

    private ApplicationContext applicationContext;

    public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {

        if(bean.getClass().getPackage().getName().equals("com.Iron.Service.Impl")){
            Object proxyInstance = Proxy.newProxyInstance(bean.getClass().getClassLoader(),
                    bean.getClass().getInterfaces(),
                    new InvocationHandler() {
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            EnhanceMethod en = applicationContext.getBean(EnhanceMethod.class);
                            en.beforeAdvice();
                            Object result = method.invoke(bean, args);
                            en.afterAdvice();
                            return result;
                        }
                    });
            return proxyInstance;
        }


        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return null;
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
